﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using FsCms.Web.Areas.Admin.Models;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using System.Security.Claims;

namespace FsCms.Web.Areas.Admin.Controllers
{
    [Area("Admin")]
    public class LoginController : Controller
    {
        [AllowAnonymous]
        [HttpGet("login")]
        public IActionResult Index(string returnUrl = "")
        {
            TempData["returnUrl"] = returnUrl;
            return View();
        }

        [AllowAnonymous]
        [HttpPost("LoginIn")]
        public async Task<IActionResult> Login([FromBody]LoginModel model)
        {
            var list = new List<dynamic> {
                new { UserName = "admin", Password = "123456", Role = "admin",Name="admin" },
                new { UserName = "system", Password = "123456", Role = "system",Name="system" }
            };
            var user = list.SingleOrDefault(s => s.UserName == model.userName && s.Password == model.password);
            if (user != null)
            {
                //用户标识
                var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
                identity.AddClaim(new Claim(ClaimTypes.Sid, model.userName));
                identity.AddClaim(new Claim(ClaimTypes.Name, user.Name));
                identity.AddClaim(new Claim(ClaimTypes.Role, user.Role));
                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
                return Json(new { status = 1 });
            }
            else
            {
                return Json(new { status = 2, errorMessage = "用户不存在或密码错误" });
            }
        }

        [HttpGet("logout")]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            return RedirectToAction("Index", "Login");
        }
    }
}
